package com.inventive.jmscache.server;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.jms.*;

/**
 * @author Grant Little <grant.little@coreservices.com.au>
 */
public class JmsCacheQueueProducer {

    private JmsCacheQueue destination;
    private QueueConnectionFactory connectionFactory;
    private QueueConnection connection;
    private QueueSession session;
    private MessageProducer producer;
    private JmsCacheServer jmsCacheServer;

    public JmsCacheQueueProducer(String destinationName) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        jmsCacheServer = applicationContext.getBean(JmsCacheServer.class);
        try {
            connectionFactory = applicationContext.getBean(JmsCacheQueueConnectionFactory.class);
            destination = new JmsCacheQueue(jmsCacheServer, destinationName);
            connection = connectionFactory.createQueueConnection();
            session = connection.createQueueSession(true, AcknowledgeMode.SESSION_TRANSACTED.ordinal());
            producer = session.createProducer(destination);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void start(int numOfMessages) {

        try {

            for (int x=0; x<numOfMessages; x++) {
                TextMessage message = session.createTextMessage("Some text " + x);
                producer.send(message);
                System.out.println("Sending message " + x);
            }
            jmsCacheServer.stop();
        } catch (JMSException e) {
            e.printStackTrace();
        }


    }
}
